﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.Text.RegularExpressions;

namespace BDAccessSharingUniqueEventReceiver
{
    public class Util
    {
        public static string StripHTML(string htmlString)
        {
            string pattern = @"<(.|\n)+?>";
            string textToReturn = Regex.Replace(htmlString, pattern, string.Empty);
            textToReturn = textToReturn.Replace("&nbsp;", "");
            return textToReturn;
        }

        public static void DeleteColumsFromLast(DataTable dt, int NumberOfRows)
        {
            for (; NumberOfRows > 0; NumberOfRows--)
                dt.Columns.RemoveAt(dt.Columns.Count - 1);
        }
        //public static void CreateLinkButton(string LinkText, string OnClickScript, GridViewRowEventArgs e, int ColumnNumber, bool EnableButton)
        //{
        //    LinkButton lb = new LinkButton();
        //    lb.Text = LinkText;
        //    if (OnClickScript.StartsWith("javascript:"))
        //        lb.OnClientClick = OnClickScript;
        //    else
        //        //lb.PostBackUrl = OnClickScript;
        //        //lb.OnClientClick = "<script language=javascript>window.location.reload( false );</script>";
        //        lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");

        //    lb.Enabled = EnableButton;
        //    e.Row.Cells[ColumnNumber].Controls.Add((Control)lb);
        //}

        //public static void CreateLinkButton(string LinkText, string OnClickScript, GridViewRow e, int ColumnNumber, bool EnableButton)
        //{
        //    LinkButton lb = new LinkButton();
        //    lb.Text = LinkText;
        //    if (OnClickScript.StartsWith("javascript:"))
        //        lb.OnClientClick = OnClickScript;
        //    else
        //        //lb.PostBackUrl = OnClickScript;
        //        //lb.OnClientClick = "<script language=javascript>window.location.reload( false );</script>";
        //        lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");

        //    lb.Enabled = EnableButton;
        //    e.Cells[ColumnNumber].Controls.Add((Control)lb);
        //}
        public static SPListItemCollection GetList(string oSite, string oWeb, SPQuery camQ, string oList)
        {
            using (SPSite sd = new SPSite(oSite))
            {
                SPWeb vBddWeb = null;

                vBddWeb = sd.AllWebs.FirstOrDefault(o => o.Title.ToUpper() == oWeb.ToUpper());

                SPList vList = vBddWeb.Lists.TryGetList(oList);
                SPListItemCollection RefinedListContent = (vList.GetItems(camQ));
                return RefinedListContent;
            }
        }

        //public SPFieldUserValueCollection GetPeopleEditorValue(PeopleEditor peopleEditorControl)
        //{
        //    SPFieldUserValueCollection ofldusercol = new SPFieldUserValueCollection();
        //    SPWeb oRootweb = SPContext.Current.Site.RootWeb;
        //    if (peopleEditorControl.IsValid)
        //    {
        //        try
        //        {
        //            //Check to make sure that there is at least one user 
        //            if (peopleEditorControl.Accounts.Count > 0)
        //            {
        //                for (int i = 0; i < peopleEditorControl.Entities.Count; i++)
        //                {
        //                    //For more than one user, this can be changed to a foreach. 
        //                    PickerEntity entity = peopleEditorControl.Entities[i] as PickerEntity;
        //                    Hashtable peopleEditorData = entity.EntityData;
        //                    string strUserLogin = entity.Key;
        //                    string strUserEmail = Convert.ToString(peopleEditorData["Email"]);
        //                    string strUserDisplayName = Convert.ToString(peopleEditorData["DisplayName"]);
        //                    SPUser SelectedUser = null;
        //                    try
        //                    {
        //                        if (peopleEditorData.Contains("SPUserID") && (!String.IsNullOrEmpty(Convert.ToString(peopleEditorData["SPUserID"]))))
        //                        {
        //                            SelectedUser = oRootweb.SiteUsers.GetByID(Convert.ToInt16(Convert.ToString(peopleEditorData["SPUserID"])));
        //                        }
        //                        else
        //                        {
        //                            SelectedUser = oRootweb.SiteUsers.GetByEmail(strUserEmail);
        //                        }
        //                    }
        //                    catch (Exception)
        //                    {
        //                        //To add the user to the site collection 
        //                        SPSecurity.RunWithElevatedPrivileges(
        //                         delegate()
        //                         {
        //                             //Could not find the user, add them to the site users. 
        //                             oRootweb.SiteUsers.Add(strUserLogin, strUserEmail, strUserDisplayName, "");
        //                             SelectedUser = oRootweb.SiteUsers.GetByEmail(strUserEmail);

        //                         });
        //                    }

        //                    ofldusercol.Add(new SPFieldUserValue(oRootweb, SelectedUser.ID, SelectedUser.Name));
        //                }

        //                return ofldusercol;
        //            }
        //            else
        //            {
        //                return ofldusercol;
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            //lblErrorMsg.Text = ex.Message;
        //            return ofldusercol;
        //        }
        //    }
        //    else
        //    {
        //        throw new Exception("People Editor Control is not valid, please correct the selection, and try again.");
        //    }
        //}

        public static int GetListItemID(string oSite, string oWeb, SPQuery camQ, string oList)
        {
            using (SPSite sd = new SPSite(oSite))
            {
                SPWeb vBddWeb = sd.AllWebs[oWeb];
                SPList vList = vBddWeb.Lists.TryGetList(oList);
                SPListItemCollection RefinedListContent = (vList.GetItems(camQ));
                var x = (from SPListItem i in RefinedListContent
                         select new
                         {
                             id = i["ID"]
                         }).FirstOrDefault();
                return int.Parse(x.id.ToString());
            }
        }

        public static SPListItem GetListItemById(string oSite, string oWeb, string oList, string id)
        {
            using (SPSite sd = new SPSite(oSite))
            {
                SPWeb vBddWeb = sd.AllWebs.FirstOrDefault(o => o.Title.ToUpper() == oWeb.ToUpper());
                SPList vList = vBddWeb.Lists.TryGetList(oList);
                SPListItemCollection RefinedListContent = vList.Items;
                SPListItem RefinedItem = RefinedListContent.GetItemById(int.Parse(id));
                return RefinedItem;
            }
        }

        public static string GetRootSiteUrl()
        {
            return "http://" + SPContext.Current.Site.HostName + ":" + SPContext.Current.Site.Port;
        }

        public static string ChangeToSpDateFormat(DateTime dateTime)
        {
            return dateTime.Year + "-" + dateTime.Month + "-" + dateTime.Day + "T00:00:00Z";
        }
        public static string ChangeToSpDateFormat(DateTime dateTime, bool start)
        {
            if (start)
                return dateTime.Year + "-" + dateTime.Month + "-" + dateTime.Day + "T00:00:00Z";
            return dateTime.Year + "-" + dateTime.Month + "-" + dateTime.Day + "T23:59:59Z";
        }

        public static string MonthDateYearFormat(DateTime dateTime)
        {
            return dateTime.Month + "/" + dateTime.Day + "/" + dateTime.Year;
        }

        //public static LinkButton ReturnALinkButton(string LinkText, string OnClickScript, bool EblButton)
        //{
        //    LinkButton lb = new LinkButton();
        //    lb.Text = LinkText;
        //    if (OnClickScript.StartsWith("javascript:"))
        //        lb.OnClientClick = OnClickScript;
        //    else
        //        lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");
        //    lb.Enabled = EblButton;
        //    lb.Visible = true;
        //    return lb;
        //}

        public static DataTable GetItemsOfSpecificType(Guid guid, string camQ, SPListTemplateType ListTemplateType)
        {
            SPSite oSiteCollection = new SPSite(guid);
            SPSiteDataQuery sQuery;
            sQuery = new SPSiteDataQuery();
            sQuery.Webs = "<Webs Scope=\"SiteCollection\">";
            if (ListTemplateType.ToString() == "Tasks")
                sQuery.Lists = "<Lists ServerTemplate='107' />"; //SPListTemplateType.Tasks
            sQuery.Query = camQ;
            return oSiteCollection.OpenWeb().GetSiteData(sQuery);
        }
        public static DataTable GetItemsOfSpecificTypeFromWeb(Guid SiteGid, Guid WebGid, string camQ, SPListTemplateType ListTemplateType)
        {
            SPWeb oWeb = new SPSite(SiteGid).OpenWeb(WebGid);
            SPSiteDataQuery sQuery;
            sQuery = new SPSiteDataQuery();
            if (ListTemplateType.ToString() == "Tasks")

                sQuery.Lists = "<Lists ServerTemplate='107' />"; //SPListTemplateType.Tasks
            else if (ListTemplateType.ToString() == "XMLForm")
                sQuery.Lists = "<Lists ServerTemplate='115' />";
            sQuery.Query = camQ;
            return oWeb.GetSiteData(sQuery);
        }
        //public static LinkButton ReturnALinkButton(string LinkText, bool EnableButton)
        //{
        //    LinkButton lb = new LinkButton();
        //    lb.Text = LinkText;
        //    lb.Enabled = EnableButton;
        //    return lb;
        //}
        public string Encode(string str)
        {
            byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(encbuff);
        }
        public string Decode(string str)
        {
            byte[] decbuff = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(decbuff);
        }
        public string GetInProgressCamQ(string uname)
        {
            return "<Where><And><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">In Progress</Value></Eq><Contains>" +
            "<FieldRef Name=\"AssignedTo\" /><Value Type=\"User\">" + uname + "</Value></Contains></And></Where>";
        }

        public string GetNotStartedCamQ(string uname)
        {
            return "<Where><And><Eq><FieldRef Name=\"Status\" /><Value Type=\"Choice\">Not Started</Value></Eq><Contains>" +
            "<FieldRef Name=\"AssignedTo\" /><Value Type=\"User\">" + uname + "</Value></Contains></And></Where>";
        }
        //public static void CreateLinkButtonWithClass(string LinkText, string OnClickScript, GridViewRowEventArgs e, int ColumnNumber, bool EnableButton, string cls)
        //{
        //    LinkButton lb = new LinkButton();
        //    lb.Text = LinkText;
        //    if (OnClickScript.StartsWith("javascript:"))
        //        lb.OnClientClick = OnClickScript;
        //    else
        //        //lb.PostBackUrl = OnClickScript;
        //        //lb.OnClientClick = "<script language=javascript>window.location.reload( false );</script>";
        //        lb.Attributes.Add("onclick", "loadFile(" + OnClickScript + ");");

        //    lb.Attributes.Add("class", cls);
        //    lb.Enabled = EnableButton;
        //    e.Row.Cells[ColumnNumber].Controls.Add((Control)lb);
        //}
        public static DataTable CreateDataColumns(params string[] colna)
        {
            DataTable dt = new DataTable();
            foreach (string item in colna)
            {
                dt.Columns.Add(item);
            }
            return dt;
        }


        //public static void ShowAllFieldsAndFieldValues(TextBox txtFieldValue, SPListItem spli)
        //{
        //    StringBuilder tx = new StringBuilder();
        //    int cont = 0;
        //    foreach (SPField item in spli.Fields)
        //    {
        //        cont++;

        //        tx.Append(cont);
        //        tx.Append(". ");
        //        tx.Append(item.Title);
        //        tx.Append("(");
        //        try { tx.Append(spli[item.Title].ToString()); }
        //        catch (Exception) { }
        //        tx.Append(")");
        //        tx.Append(item.StaticName + Environment.NewLine);

        //    }
        //    txtFieldValue.Text = tx.ToString();
        //}

        public static string GetFieldInternalName(string SiteUrl, string WebName, string ListName, string FieldExternalName)
        {
            string rtn = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                rtn = new SPSite(SiteUrl).AllWebs.FirstOrDefault(o => o.Title.ToUpper() == WebName.ToUpper()).Lists.TryGetList(ListName).Fields[FieldExternalName].InternalName;
            });
            return rtn;
        }

        public static SPWeb GetWebFromList(string DepartmentTitle)
        {
            SPSite oSite = new SPSite(GetRootSiteUrl());
            SPQuery camQ = new SPQuery();
            camQ.Query = "<Where><Eq><FieldRef Name=\"Department_x0020_in_x0020_User_x\" /><Value Type=\"Text\">" +
                DepartmentTitle + "</Value></Eq></Where>";

            SPWeb oWeb;
            try
            {
                SPListItem li = oSite.RootWeb.Lists.TryGetList("Departments_Projects_Info").GetItems(camQ)[0];
                oWeb = oSite.OpenWeb(li["Site URL"].ToString());
            }
            catch (ArgumentOutOfRangeException) { oWeb = null; }
            return oWeb;
        }
    }
}
